// pages/orderList/orderList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //状态筛选
    option: [
      { text: '未完成绑定', value: 1 },
      { text: '完成绑定', value: 0 },
      { text: '全部', value: 'a' }
    ],
    //发货状态筛选
    sendOption: [
      { text: '未发货', value: 1 },
      { text: '已发货', value: 0 },
      { text: '全部', value: 'b' }
    ],
    value: 1,
    sendValue:1,
    //用户
    user:null,
    authority:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      user:app.globalData.userInfo,
      authority:app.globalData.authority
    })
    //获取列表数据
    this.refreshListAndPage();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  //获取列表数据
  getList(){
    //this.data.list=[];
    console.log(this.data.sendValue);
    let user=app.globalData.userInfo;
    let authority = app.globalData.authority
    console.log("-------------------------------------");
    console.log(authority.iot.purchaseOrder.queryAll == null)
    let complex =[];
    console.log(user);
    //平台用户或有jnbDepartId的厂家才进行查询请求
    if(user.departObj[0].type==1 || (user.departObj[0].type==2 && user.depart)){
      Toast.loading({
        duration: 0,
        forbidClick: true,
        message: '加载中...'
      });


      let param={
        isAuth:false,
        className:'purchaseOrder',
        data:{
          selectFields:["id","orderNo","member","createTime","sellAmount","purchaseAmount","state","member","orderId","supplier",
          "address","businessType","orderNo","relationOrderNo","kind","salesman","detail","project","servicer","numbers","send","editerIds",
          "contractDepart","cleaningSupplier","cleaningSupplierProject","ownerIds","sendNumbers"],
        page:{
            page:this.data.page,
            pageSize:10
          },
          state:{">":1},
          sort:{"createTime":-1}
          //"supplier.id":user.departObj[0].id  
        }
      }
      
      if(authority.iot.purchaseOrder.queryAll == null) {
        param.data['supplier.id']=user.departObj[0].id 
      }

      //筛选状态
      if(this.data.value!='a'){
        param.data.numbers={"!=":0}
      }

      if(this.data.value==0){
        param.data.numbers=0
      }

      if(this.data.sendValue !='b'){
          param.data.sendNumbers={"!=":0}
      }

      if(this.data.sendValue == 0){
        param.data.sendNumbers=0
      }


      

      //搜索
      if (this.data.searchValue) {
        let words=this.data.searchValue;
        let complex = [{
          "or": {
            "address.consignee": '%' + words + '%',
            "address.receivingPhone": '%' + words + '%'
          }
        }];
        param.data.complex = complex;
      }
      console.log(param);
      CommonService.goFindList(param).then(res=>{
        Toast.clear();
        console.log(res);
        if(res.data.data && res.data.data.result && res.data.data.result.length){
          let result=res.data.data.result;
          console.log('订单列表');
          console.log(result);

          //没有确认项目的加一个标识
          result.forEach(item => {
            let count = 0
            if(item.detail && item.detail.length>0){
              item.detail.forEach(val => {
                  count+= val.num;
              })
              item.count = count;
            }
            // console.log(item);
            // let list=item;

            // if (item.items && item.items.length){
            //   let list=item.items;
            //   let flag=list.some(item => {
            //       return (item.projectId)&&(item.projectId!=0)
            //   })
            //   if(!flag){
            //     item.unconfirmedProject=true;
            //   }
            // }
          });
         
          this.setData({
            list: this.data.list.concat(result)
          })
          console.log(this.data.list);
        }else{
          this.setData({
            notMore: false
          })
          if(this.data.page==1){
            this.setData({
              showNothing: true
            })
          }else{
            Toast.fail('没有更多了');
          }
        }
      }).catch((error) => {
        Toast.clear();
        this.setData({
          showNothing: true
        })
      })
    }else{
      this.setData({
        showNothing: true
      })
    }
  },

  send(e){
    let detail=e.currentTarget.dataset.detail;
    detail.detail.forEach(val => {
      if(val.spu.imgUrl != null && val.spu.imgUrl !=''){
        val.spu.imgUrl =  val.spu.imgUrl.split("?")[0];
      }
    })
    
    wx.navigateTo({
      url: "/packageA/pages/equipmentSend/equipmentSend?detail="+JSON.stringify(detail)
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail,
    });

    // if(!e.detail){
    //   //刷新列表和页码
    //   this.refreshListAndPage();
    // }
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //跳转订单设备
  goToEquipment(e){
     let detail=e.currentTarget.dataset.detail;
     detail.detail.forEach(val => {
      if(val.spu.imgUrl != null && val.spu.imgUrl !=''){
        val.spu.imgUrl =  val.spu.imgUrl.split("?")[0];
      }
    })
     console.log(detail);
     console.log(JSON.stringify(detail));
    wx.navigateTo({
			url: "/packageA/pages/orderDetailEquipment/detailEquipment?obj="+JSON.stringify(detail)
		})
  },

  //选择状态
  onChange({detail}) {
    this.setData({
      value: detail
    });
    this.refreshListAndPage();
  },

  onSendChange({detail}) {
    this.setData({
      sendValue: detail
    });
    this.refreshListAndPage();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})
